<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="资产编号" prop="no">
                <el-input v-model="queryParams.no" placeholder="请输入资产编号(模糊查)" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="资产名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入资产名称(模糊查)" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="资产类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择资产类型" clearable>
                    <el-option v-for="dict in dict.type.basic_asset_type_dict" :key="dict.value" :label="dict.label"
                               :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="资产状态" prop="status">
                 <el-select v-model="queryParams.status" placeholder="请选择资产状态" clearable>
                     <el-option v-for="dict in dict.type.basic_asset_status_dict" :key="dict.value" :label="dict.label"
                                :value="dict.value"/>
                 </el-select>
             </el-form-item>
             <el-form-item label="创建时间" prop="daterangeCreateTime">
                 <el-date-picker
                     v-model="daterangeCreateTime"
                     type="daterange"
                     range-separator="至"
                     start-placeholder="开始日期"
                     end-placeholder="结束日期"
                     format="yyyy-MM-dd"
                     value-format="yyyy-MM-dd"
                     clearable>
                 </el-date-picker>
             </el-form-item>
             <el-form-item>
                 <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                 <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
             </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['basic:inventory:add']">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                           v-hasPermi="['basic:inventory:edit']">修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                           @click="handleDelete" v-hasPermi="['basic:inventory:remove']">删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleImport"
                           v-hasPermi="['basic:inventory:import']">导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                           v-hasPermi="['basic:inventory:export']">导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <!--              <el-table-column label="主键" align="center" prop="id" />-->
            <el-table-column label="资产编号" align="center" prop="no"/>
            <el-table-column label="资产条码" align="center" prop="uniqueIdentifier"/>
            <el-table-column label="资产名称" align="center" prop="name"/>
            <el-table-column label="型号" align="center" prop="model"/>
            <el-table-column label="耗材单位" align="center" prop="consumeUnit"/>
            <el-table-column label="资产类型" align="center" prop="type">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_asset_type_dict" :value="scope.row.type"/>
                </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="number"/>
            <el-table-column label="管理员" align="center" prop="administrator"/>
            <el-table-column label="管理部门" align="center" prop="manageDeptId">
                <template slot-scope="scope">
                    <span>{{ getDeptName(scope.row.manageDeptId) }}</span>
                </template>
            </el-table-column>

            <el-table-column label="使用人" align="center" prop="charge"/>
            <el-table-column label="存放地点" align="center" prop="storagePlace"/>
            <el-table-column label="资产状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_asset_status_dict" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="单价" align="center" prop="price"/>
            <el-table-column label="计量单位" align="center" prop="unitOfMeasure"/>
            <el-table-column label="所属分类" align="center" prop="assetCategory"/>
            <el-table-column label="赋码日期" align="center" prop="codingDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.codingDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所属仓库" align="center" prop="affiliatedWarehouse"/>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="体积" align="center" prop="volume"/>
            <el-table-column label="重量" align="center" prop="weight"/>
            <el-table-column label="功率" align="center" prop="power"/>
            <el-table-column label="生成厂家" align="center" prop="vender"/>
            <el-table-column label="收货日期" align="center" prop="receiptDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.receiptDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="启用日期" align="center" prop="activationDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.activationDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="入库日期" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="资产来源" align="center" prop="source"/>
            <el-table-column label="购入原因" align="center" prop="purchaseReason"/>
            <el-table-column label="交接人" align="center" prop="handoverPerson"/>
            <el-table-column label="接收人" align="center" prop="recipient"/>
            <el-table-column label="货架号/箱号" align="center" prop="shelfOrBoxNumber"/>
            <!--              <el-table-column label="存储路径" align="center" prop="attachmentUrl" />-->
            <!--              <el-table-column label="存储文件名" align="center" prop="attachmentName" />-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['basic:inventory:edit']">修改
                    </el-button>

                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['basic:inventory:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <!-- 添加或修改固定资产管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="资产名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入资产名称"/>
                        </el-form-item>

                        <el-form-item label="所属分类" prop="assetCategory">
                            <el-input v-model="form.assetCategory" placeholder="请输入所属分类"/>
                        </el-form-item>

                        <el-form-item label="数量" prop="number">
                            <el-input-number v-model="form.number" :min="1" :step="1" placeholder="请输入数量" style="width: 100%"/>
                        </el-form-item>

                        <el-form-item label="计量单位" prop="unitOfMeasure">
                            <el-input v-model="form.unitOfMeasure" placeholder="请输入计量单位"/>
                        </el-form-item>

                        <el-form-item label="资产编号" prop="no">
                            <el-input v-model="form.no" placeholder="请输入资产编号"/>
                        </el-form-item>
                        <el-form-item label="资产条码" prop="uniqueIdentifier">
                            <el-input v-model="form.uniqueIdentifier" placeholder="请输入资产条码"/>
                        </el-form-item>

                        <el-form-item label="型号" prop="model">
                            <el-input v-model="form.model" placeholder="请输入型号"/>
                        </el-form-item>

                        <el-form-item label="耗材单位" prop="consumeUnit">
                            <el-input v-model="form.consumeUnit" placeholder="请输入耗材单位"/>
                        </el-form-item>

                        <el-form-item label="资产类型" prop="type">
                            <el-select v-model="form.type" placeholder="请选择资产类型" style="width: 100%">
                                <el-option
                                    v-for="dict in dict.type.basic_asset_type_dict"
                                    :key="dict.value"
                                    :label="dict.label"
                                    :value="parseInt(dict.value)"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="管理员" prop="administrator">
                            <el-input v-model="form.administrator" placeholder="请输入管理员"/>
                        </el-form-item>

                         <!-- 管理部门 -->
                        <el-form-item label="管理部门" prop="manageDeptId">
                            <treeselect v-model="form.manageDeptId" :options="deptOptions" :show-count="true" placeholder="请选择管理部门" style="width: 220px"/>
                        </el-form-item>

                        <el-form-item label="存放地点" prop="storagePlace">
                            <el-input v-model="form.storagePlace" placeholder="请输入存放地点"/>
                        </el-form-item>
                        <el-form-item label="货架/箱号" prop="shelfOrBoxNumber">
                            <el-input v-model="form.shelfOrBoxNumber" placeholder="请输入货架/箱号"/>
                        </el-form-item>
                        <el-form-item label="接收人" prop="recipient">
                            <el-input v-model="form.recipient" placeholder="请输入接收人"/>
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入备注"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="资产状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                    v-for="dict in dict.type.basic_asset_status_dict"
                                    :key="dict.value"
                                    :label="parseInt(dict.value)"
                                >
                                    {{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="单价" prop="price">
                            <el-input-number v-model="form.price" :min="0.01" :step="0.01" :precision="2" placeholder="请输入单价" style="width: 100%"/>
                        </el-form-item>

                        <el-form-item label="所属仓库" prop="affiliatedWarehouse">
                            <el-input v-model="form.affiliatedWarehouse" placeholder="请输入所属仓库"/>
                        </el-form-item>

                        <el-form-item label="使用人" prop="charge">
                            <el-input v-model="form.charge" placeholder="请输入使用人"/>
                        </el-form-item>

                        <el-form-item label="赋码日期" prop="codingDate">
                            <el-date-picker clearable v-model="form.codingDate" type="date" value-format="yyyy-MM-dd"
                                            placeholder="请选择赋码日期" style="width: 100%">
                            </el-date-picker>
                        </el-form-item>

                        <el-form-item label="体积" prop="volume">
                            <el-input v-model="form.volume" placeholder="请输入体积"/>
                        </el-form-item>
                        <el-form-item label="重量" prop="weight">
                            <el-input v-model="form.weight" placeholder="请输入重量"/>
                        </el-form-item>
                        <el-form-item label="功率" prop="power">
                            <el-input v-model="form.power" placeholder="请输入功率"/>
                        </el-form-item>
                        <el-form-item label="厂家" prop="vender">
                            <el-input v-model="form.vender" placeholder="请输入厂家"/>
                        </el-form-item>
                        <el-form-item label="到货日期" prop="receiptDate">
                            <el-date-picker clearable
                                            v-model="form.receiptDate"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="请选择到货日期"
                                            style="width: 100%">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="启用日期" prop="activationDate">
                            <el-date-picker clearable
                                            v-model="form.activationDate"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="请选择启用日期"
                                            style="width: 100%">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="来源" prop="source">
                            <el-input v-model="form.source" placeholder="请输入来源"/>
                        </el-form-item>
                        <el-form-item label="移交人" prop="handoverPerson">
                            <el-input v-model="form.handoverPerson" placeholder="请输入移交人"/>
                        </el-form-item>
                        <el-form-item label="购买原因" prop="purchaseReason">
                            <el-input v-model="form.purchaseReason" placeholder="请输入购买原因"/>
                        </el-form-item>



                        <el-form-item label="附件" prop="attachment">
                            <!-- 当有附件时显示文件信息和下载/删除按钮 -->
                            <div v-if="form.attachmentUrl">
                                <div style="display: flex; align-items: center; gap: 10px;">
                                    <i class="el-icon-document" style="color: #409EFF;"></i>
                                    <a
                                        :href="form.attachmentUrl"
                                        :download="form.attachmentName"
                                        style="color: #409EFF; text-decoration: none;"
                                        @click="handleDownload"
                                    >
                                        {{ form.attachmentName }}
                                    </a>
                                    <el-button
                                        size="small"
                                        type="danger"
                                        plain
                                        @click="handleDeleteAttachment"
                                        :loading="loading"
                                    >
                                        <i class="el-icon-delete"></i>
                                        删除
                                    </el-button>
                                </div>
                            </div>
                            <!-- 当没有附件时显示上传组件 -->
                            <div v-else>
                                <el-upload
                                    ref="uploadRef"
                                    :before-upload="beforeUpload"
                                    :on-success="handleUploadSuccess"
                                    :on-remove="handleRemove"
                                    :auto-upload="false"
                                    accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png"
                                    action="#"
                                    list-type="text"
                                    :limit="1">
                                    <el-button size="small" type="primary" plain>
                                        <i class="el-icon-upload"></i>
                                        选择文件
                                    </el-button>
                                    <div class="el-upload__tip" style="line-height: 1.2; margin-top: 5px;">
                                        <div>支持pdf/doc/docx/xls/xlsx/jpg/jpeg/png</div>
                                        <div>单个≤10MB</div>
                                    </div>
                                </el-upload>
                            </div>
                        </el-form-item>

                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 固定资产导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
                       :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listInventory, getInventory, delInventory, addInventory, updateInventory} from "@/api/basic/inventory";
import {uploadToMinIO} from "@/api/common/minio";
import {getToken} from "@/utils/auth";
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
    name: "Inventory",
    dicts: ['basic_asset_type_dict', 'basic_asset_status_dict'],
    components: {Treeselect},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 固定资产管理表格数据
            inventoryList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 创建时间范围
            daterangeCreateTime: [],
            deptOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                no: null,
                uniqueIdentifier: null,
                name: null,
                model: null,
                consumeUnit: null,
                type: null,
                number: null,
                administrator: null,
                manageDeptId: null,
                charge: null,
                storagePlace: null,
                status: null,
                price: null,
                deleted: null,
                unitOfMeasure: null,
                assetCategory: null,
                usageStatus: null,
                codingDate: null,
                affiliatedWarehouse: null,
                volume: null,
                weight: null,
                power: null,
                vender: null,
                receiptDate: null,
                activationDate: null,
                source: null,
                purchaseReason: null,
                handoverPerson: null,
                recipient: null,
                shelfOrBoxNumber: null,
                attachmentUrl: null,
                attachmentName: null
            },
            // 表单参数
            form: {},
            // 选中的查询字段
            selectedQueryFields: [],
            // 表单校验
            rules: {
                name: [
                    {required: true, message: "资产名称不能为空", trigger: "blur"}
                ],
                assetCategory: [
                    {required: true, message: "所属分类不能为空", trigger: "blur"}
                ],
                number: [
                    {required: true, message: "数量不能为空", trigger: "change"},
                    {type: 'number', min: 1, message: "数量必须为大于0的数字", trigger: "change"}
                ],
                status: [
                    {required: true, message: "使用状态不能为空", trigger: "change"}
                ],

                price: [
                    {required: true, message: "单价不能为空", trigger: "change"},
                    {type: 'number', min: 0.01, message: "单价必须为大于0的数字", trigger: "change"}
                ],

                affiliatedWarehouse: [
                    {required: true, message: "所属仓库不能为空", trigger: "blur"}
                ],
            },
            // 资产导入参数
            upload: {
                // 是否显示弹出层（资产导入）
                open: false,
                // 弹出层标题（资产导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的资产数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {Authorization: "Bearer " + getToken()},
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/basic/inventory/importData"
            },
        };
    },
    created() {
        //获取部门树结构
        this.getDeptTree();
        this.getList();
    },
    methods: {
        // 处理下载附件
        handleDownload() {
            console.log('开始下载文件:', this.form.attachmentName);
            // 使用原生的下载方式，让浏览器处理下载
            const link = document.createElement('a');
            link.href = this.form.attachmentUrl;
            link.download = this.form.attachmentName;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            console.log('下载链接已触发:', this.form.attachmentUrl);
        },

        // 删除附件
        handleDeleteAttachment() {
            this.$confirm('确认要删除该附件吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log('删除附件:', this.form.attachmentName);
                // 清空附件信息
                this.form.attachmentUrl = null;
                this.form.attachmentName = null;

                // 清空上传组件的文件列表
                if (this.$refs.uploadRef) {
                    this.$refs.uploadRef.clearFiles();
                }

                this.$message.success('附件删除成功');
                console.log('附件已删除，URL和Name已设为null');
            }).catch(() => {
                console.log('用户取消删除附件');
                this.$message.info('已取消删除');
            });
        },

        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },

        /** 查询固定资产管理列表 */
        getList() {
            this.loading = true;
            // 处理时间范围查询参数
            if (this.daterangeCreateTime && this.daterangeCreateTime.length === 2) {
                this.queryParams.params = {};
                this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
                this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
            } else {
                this.queryParams.params = null;
            }
            listInventory(this.queryParams).then(response => {
                this.inventoryList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                no: null,
                uniqueIdentifier: null,
                name: null,
                model: null,
                consumeUnit: null,
                type: null,
                number: null,
                administrator: null,
                manageDeptId: null,
                charge: null,
                storagePlace: null,
                status: null,
                price: null,
                deleted: null,
                createTime: null,
                unitOfMeasure: null,
                assetCategory: null,
                usageStatus: null,
                codingDate: null,
                affiliatedWarehouse: null,
                remark: null,
                volume: null,
                weight: null,
                power: null,
                vender: null,
                receiptDate: null,
                activationDate: null,
                source: null,
                purchaseReason: null,
                handoverPerson: null,
                recipient: null,
                shelfOrBoxNumber: null,
                attachmentUrl: null,
                attachmentName: null
            };
            this.resetForm("form");

            // 清空上传组件的文件列表
            if (this.$refs.uploadRef) {
                this.$refs.uploadRef.clearFiles();
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            // 手动重置时间范围字段
            this.daterangeCreateTime = [];
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加固定资产管理";
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            if (row && row.id) {
                // 深拷贝数据并处理数据类型，确保number和price为数字
                this.form = {
                    id: row.id,
                    no: row.no,
                    uniqueIdentifier: row.uniqueIdentifier,
                    name: row.name,
                    model: row.model,
                    consumeUnit: row.consumeUnit,
                    type: row.type ? parseInt(row.type) : null,
                    number: row.number ? parseInt(row.number) : 1,
                    administrator: row.administrator,
                    manageDeptId: row.manageDeptId,
                    charge: row.charge,
                    storagePlace: row.storagePlace,
                    status: row.status ? parseInt(row.status) : null,
                    price: row.price ? parseFloat(row.price) : null,
                    deleted: row.deleted,
                    unitOfMeasure: row.unitOfMeasure,
                    assetCategory: row.assetCategory,
                    usageStatus: row.usageStatus,
                    codingDate: row.codingDate,
                    affiliatedWarehouse: row.affiliatedWarehouse,
                    remark: row.remark,
                    volume: row.volume,
                    weight: row.weight,
                    power: row.power,
                    vender: row.vender,
                    receiptDate: row.receiptDate,
                    activationDate: row.activationDate,
                    source: row.source,
                    purchaseReason: row.purchaseReason,
                    handoverPerson: row.handoverPerson,
                    recipient: row.recipient,
                    shelfOrBoxNumber: row.shelfOrBoxNumber,
                    attachmentUrl: row.attachmentUrl,
                    attachmentName: row.attachmentName,
                    createTime: row.createTime
                };
            } else if (this.ids.length === 1) {
                // Get data from inventoryList based on selected ID
                const selectedItem = this.inventoryList.find(item => item.id === this.ids[0]);
                if (selectedItem) {
                    this.form = {
                        id: selectedItem.id,
                        no: selectedItem.no,
                        uniqueIdentifier: selectedItem.uniqueIdentifier,
                        name: selectedItem.name,
                        model: selectedItem.model,
                        consumeUnit: selectedItem.consumeUnit,
                        type: selectedItem.type ? parseInt(selectedItem.type) : null,
                        number: selectedItem.number ? parseInt(selectedItem.number) : 1,
                        administrator: selectedItem.administrator,
                        manageDeptId: selectedItem.manageDeptId,
                        charge: selectedItem.charge,
                        storagePlace: selectedItem.storagePlace,
                        status: selectedItem.status ? parseInt(selectedItem.status) : null,
                        price: selectedItem.price ? parseFloat(selectedItem.price) : null,
                        deleted: selectedItem.deleted,
                        unitOfMeasure: selectedItem.unitOfMeasure,
                        assetCategory: selectedItem.assetCategory,
                        usageStatus: selectedItem.usageStatus,
                        codingDate: selectedItem.codingDate,
                        affiliatedWarehouse: selectedItem.affiliatedWarehouse,
                        remark: selectedItem.remark,
                        volume: selectedItem.volume,
                        weight: selectedItem.weight,
                        power: selectedItem.power,
                        vender: selectedItem.vender,
                        receiptDate: selectedItem.receiptDate,
                        activationDate: selectedItem.activationDate,
                        source: selectedItem.source,
                        purchaseReason: selectedItem.purchaseReason,
                        handoverPerson: selectedItem.handoverPerson,
                        recipient: selectedItem.recipient,
                        shelfOrBoxNumber: selectedItem.shelfOrBoxNumber,
                        attachmentUrl: selectedItem.attachmentUrl,
                        attachmentName: selectedItem.attachmentName,
                        createTime: selectedItem.createTime
                    };
                }
            } else {
                this.$message.warning("请选择一条数据进行修改");
                return;
            }
            this.open = true;
            this.title = "修改固定资产管理";
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除固定资产管理编号为"' + ids + '"的数据项？').then(function () {
                return delInventory(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('basic/inventory/export', {
                ...this.queryParams
            }, `资产管理_${new Date().getTime()}.xlsx`)
        },
                /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "固定资产导入";
            this.upload.open = true;
        },

        /** 下载模板操作 */
        importTemplate() {
            this.download('basic/inventory/importTemplate', {}, `固定资产模板_${new Date().getTime()}.xlsx`)
        },

        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },

        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },

        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();

            // 对导入结果进行校验
            this.validateImportResult(response);

            // 创建一个新的对话框实例，使用更大的宽度和适当的样式
            this.$alert("<div style='overflow: auto;max-width: none; width: 1200px;max-height: 70vh;padding: 10px 20px 0;white-space: pre-wrap;word-break: break-word;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true, customClass: 'wide-alert', center: false});
            this.getList();
        },

        // 校验导入结果
        validateImportResult(response) {
            if (!response || !response.data) {
                return;
            }

            const validationRules = {
                name: { required: true, type: 'string', fieldName: '资产名称' },
                type: { required: true, type: 'number', fieldName: '资产类型' },
                number: { required: true, type: 'number', fieldName: '数量' },
                status: { required: true, type: 'number', fieldName: '资产状态' },
                price: { required: true, type: 'number', fieldName: '单价' },
                manageDeptId: { required: true, type: 'number', fieldName: '管理部门' }
            };

            const errors = [];

            // 检查是否包含导入数据
            if (Array.isArray(response.data) && response.data.length > 0) {
                response.data.forEach((item, index) => {
                    const rowNumber = index + 1; // 表格行号从1开始

                    Object.keys(validationRules).forEach(field => {
                        const rule = validationRules[field];
                        const value = item[field];

                        // 检查是否为空
                        if (rule.required && (value === null || value === undefined || value === '')) {
                            errors.push(`第${rowNumber}行：${rule.fieldName}不能为空`);
                            return;
                        }

                        // 如果有值，检查数据类型
                        if (value !== null && value !== undefined && value !== '') {
                            const actualType = typeof value;
                            if (rule.type === 'number' && isNaN(Number(value))) {
                                errors.push(`第${rowNumber}行：${rule.fieldName}必须是数字类型，当前值为"${value}"`);
                            } else if (rule.type === 'string' && actualType !== 'string') {
                                errors.push(`第${rowNumber}行：${rule.fieldName}必须是字符串类型`);
                            }
                        }
                    });
                });
            }

            // 如果有校验错误，显示错误信息
            if (errors.length > 0) {
                const errorMessage = errors.join('\n');
                this.$alert(errorMessage, "导入数据校验失败", {
                    confirmButtonText: '确定',
                    type: 'error',
                    customClass: 'wide-alert',
                    center: false,
                    dangerouslyUseHTMLString: true,
                    callback: action => {
                        this.getList(); // 即使校验失败也刷新列表
                    }
                });
                console.error('导入数据校验失败:', errors);
            }
        },

        // 文件上传前的验证
        beforeUpload(file) {
            const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                                 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                                 'image/jpeg', 'image/png'].includes(file.type);
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isValidType) {
                this.$message.error('上传文件只能是 pdf/doc/docx/xls/xlsx/jpg/jpeg/png 格式!');
                return false;
            }
            if (!isLt10M) {
                this.$message.error('上传文件大小不能超过 10MB!');
                return false;
            }
            return true; // 返回true表示允许上传，但需要手动处理上传
        },
        // 提交按钮
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.loading = true;
                    // 检查是否存在上传组件引用
                    const uploadRef = this.$refs.uploadRef;
                    if (uploadRef && uploadRef.uploadFiles && uploadRef.uploadFiles.length > 0) {
                        const uploadFiles = uploadRef.uploadFiles;
                        const pendingFiles = uploadFiles.filter(file => !file.response); // 过滤出还没有上传成功的文件

                        if (pendingFiles.length > 0) {
                            // 批量上传所有待上传的文件
                            const uploadPromises = pendingFiles.map(file => {
                                return uploadToMinIO(file.raw).then(response => {
                                    // 更新文件的响应数据
                                    file.response = response;
                                    return response;
                                }).catch(error => {
                                    this.$message.error(`文件 ${file.name} 上传失败: ${error.message || '未知错误'}`);
                                    throw error;
                                });
                            });

                            // 等待所有文件上传完成
                            Promise.all(uploadPromises).then(results => {
                                // 设置表单的附件信息
                                this.form.attachmentUrl = results[0].data;
                                this.form.attachmentName = uploadFiles.map(f => f.name).join(',');
                                // 提交表单
                                this.submitFormData();
                            }).catch(error => {
                                this.loading = false;
                                this.$message.error('文件上传失败，请重试');
                            });
                            return; // 提前返回，等待文件上传完成后再提交
                        }
                    }

                    console.log('没有文件需要上传，直接提交表单');
                    // 如果没有文件需要上传，直接提交表单
                    this.submitFormData();
                }
            });
        },

        // 提交表单数据
        submitFormData() {
            if (this.form.id != null) {
                updateInventory(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                    this.loading = false;
                }).catch(error => {
                    console.error('更新失败:', error);
                    this.loading = false;
                    this.$message.error('更新失败');
                });
            } else {
                addInventory(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                    this.loading = false;
                }).catch(error => {
                    console.error('新增失败:', error);
                    this.loading = false;
                    this.$message.error('新增失败');
                });
            }
        },
        // 文件上传成功
        handleUploadSuccess(response, file, fileList) {
            console.log('文件上传成功:', response);
            // 将上传的文件信息保存到表单中
            if (response && response.url) {
                this.form.attachmentUrl = response.url;
                this.form.attachmentName = file.name;
            }
        },
        // 移除文件
        handleRemove(file, fileList) {
            console.log('移除文件:', file);
            // 单文件上传，直接清空表单中的附件信息
            this.form.attachmentUrl = null;
            this.form.attachmentName = null;
        },

        // 根据科室ID获取科室名称
        getDeptName(deptId) {
            if (!deptId) return '';
            let deptName = '';
            const findDeptName = (nodes) => {
                for (const node of nodes) {
                    if (node.id === deptId) {
                        deptName = node.label;
                        return true;
                    }
                    if (node.children && node.children.length > 0) {
                        if (findDeptName(node.children)) {
                            return true;
                        }
                    }
                }
                return false;
            };
            if (this.deptOptions && this.deptOptions.length > 0) {
                findDeptName(this.deptOptions);
            }
            return deptName;
        }
    }
};
</script>

<style>
/* 为导入结果弹窗添加宽样式 */
.wide-alert {
    width: 700px !important;
    max-width: none !important;
}
.wide-alert .el-message-box__content {
    padding: 20px;
}
</style>
